package com.cac.demo.controller.backReceive;

import com.alibaba.fastjson.JSON;
import com.cac.demo.controller.CallInterFace.SendMaterialInterface;
import com.cac.demo.newCode.materialStorage.dto.MaterialDTO;
import com.cac.demo.newCode.utils.MaterialUtil;
import com.cac.demo.service.backReceive.BackReceiveService;
import com.cac.demo.util.adapter.PageParameter;
import com.cac.demo.util.adapter.QueryReqBean;
import com.cac.demo.util.adapter.QueryRespBean;
import com.cac.demo.util.adapter.ResponseMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/BackReceive/")
@RestController
@Slf4j
public class BackReceiveRest {
    @Autowired
    private BackReceiveService backReceiveService;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private Environment environment;
    @Autowired
    private SendMaterialInterface sendMaterialInterface;
    @Value("${pathProperty.isTest}")
    private boolean isTest;
    @Resource
    private MaterialUtil materialUtil;


    //退库单查询
    @PostMapping("/searchMaterail")
    public ResponseMsg<QueryRespBean<HashMap>> searchBackMaterial(@RequestBody HashMap map) {
        ResponseMsg<QueryRespBean<HashMap>> responseMsg = new ResponseMsg<>();
        String page = JSON.toJSONString(map.get("pageParameter"));
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        HashMap searchParams = JSON.parseObject(searchParamsParams, HashMap.class);
        PageParameter pageParameter = JSON.parseObject(page, PageParameter.class);
        QueryReqBean<HashMap> queryReqBean = new QueryReqBean<>();
        queryReqBean.setPageParameter(pageParameter);
        queryReqBean.setSearchParams(searchParams);
        QueryRespBean<HashMap> result = backReceiveService.searchBackMaterial(queryReqBean, searchParams);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    @PostMapping("/searchByBarcode")
    public ResponseMsg<List<HashMap>> searchByBarcodeFS(@RequestBody Map map) {
        ResponseMsg<List<HashMap>> responseMsg = new ResponseMsg<>();
         MaterialDTO materialDTO = materialUtil.getMaterialDTO(map.get("barCode").toString());
        String barcode = materialDTO.getBarCode();
        List<HashMap> result = backReceiveService.searchBackMaterialByBarcode(barcode);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    //退库接收物料
    @PostMapping("/changeAccType")
    @Transactional
    public ResponseMsg<String> changeBackType(@RequestBody Map map) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        log.info("退库参数：" + map.toString() + "  00");
        String barcode = (String) map.get("barcode");
        int returnQty = (int) map.get("returnQty");
        String id = (String) map.get("wmsDeliveryPlanId");
        String status = (String) map.get("status");
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        log.info("IP" + IP);
        String account = (String) request.getSession().getAttribute("account");
        try {
            //修改交接单状态
            int result = backReceiveService.changeBackType(barcode, account, returnQty, IP, id, status);
            if (result == 1) {
                //生成receDetail数据
                backReceiveService.insertReceDetail(id);
                //接收回传MES
                HashMap paramMap = new HashMap();
                //网闸查询场景编码
//                if(isTest){
//                    paramMap.put("dmsCode", "ms_tkjscs");
//                }else {
//                    paramMap.put("dmsCode", "ms_tkjs");
//                }
                paramMap.put("dmsCode", "ms_tkjs");
                //网闸查询数据SQL所需条件
                paramMap.put("WMS_DELIVERY_PLAN_ID", id);
                HashMap interfaceMap = new HashMap();
                //网闸数据打包接口所需参数
                interfaceMap.put("code", "getMatchData");
                interfaceMap.put("name", "获取数据配套场景的配套数据");
                interfaceMap.put("parameters", paramMap);
                //发送文件到MES的func
                interfaceMap.put("func", environment.getProperty("backMES.func"));
                interfaceMap.put("sendScenario", "退库接收");
                log.info("=====================" + interfaceMap.toString());
                //101-MES发送文件接口
                HashMap rsl = sendMaterialInterface.SendFileInterface(interfaceMap);
                if (rsl.get("retCode").equals("200")) {
                    responseMsg.setRetCode("200").setMessage("操作成功！");
                } else {
                    responseMsg.setRetCode("201").setMessage("数据回传MES失败！");
                }
            } else {
                responseMsg.setRetCode("201").setMessage("条码不存在！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseMsg.setRetCode("201");
        } finally {
            return responseMsg;
        }
    }
}
